import re
import json


def process_llm_history(config, paras): # under development, if we need to parse the history
    his_record = ''
    try:
        his_k = config['HISTORY_K']
        histories = paras['histories']
        try:
            use_his = paras['use_his']
        except:
            use_his = False
            
        if len(histories)>=1 and use_his:
            his_infos = histories[-his_k :]
            for i, his in enumerate(his_infos):
                his_record += f"""历史提问{i+1}：{his[0]}    历史回答{i+1}：{his[1]}\n"""
            his_record = his_record.strip()
    except:
        pass
    return his_record


def eval_response(str_answer, config=None, answer_key=None):
    # str_answer = re.sub(r'\s+', '', str_answer)        
    str_answer = str_answer.replace("'", '"').replace("#", '').replace("**", '').strip()
    # print('\t' + str_answer + '\n')
    
    try:
        answer = json.loads(str_answer)
        print('\t successfully find json marks and parse the response')
    except:
        print('\t regular parsing fails, try finding json marks...')

        matches = re.findall(r'```json\s*(.+?)\s*```', str_answer, re.DOTALL)
        if len(matches)==0:
            matches = re.findall(r'```json({.+?})```', str_answer, re.DOTALL)
            if len(matches)==0:
                str_answer = str_answer.replace('```json', '').strip()
                str_answer = str_answer.replace('```', '').strip()
            else:
                str_answer = matches[0]
        else:
            str_answer = matches[0]
            
        try:
            answer = json.loads(str_answer)
        except:
            print('\t no json object parsed, using original input answer')
            return str_answer   
    if not answer_key==None:
        answer = answer[answer_key]
    return answer
    
            
    
    


